package com.zzh.myapplication.fragment;

import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LayerDrawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.SpinnerStyle;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.zzh.myapplication.R;
import com.zzh.myapplication.adapter.UserEditAdapter;
import com.zzh.myapplication.utlis.ColorUtil;
import com.zzh.myapplication.utlis.DensityUtil;
import com.zzh.myapplication.utlis.DividerGridItemDecoration;
import com.zzh.myapplication.utlis.DynamicTimeFormat;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Random;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * @author zzh
 * @Name:
 * @Description:
 * @date
 * @time
 * @copyright
 */
public class OrderFragment extends Fragment implements View.OnClickListener {
    @Bind(R.id.refreshLayout)
    RefreshLayout mRefreshLayout;
    @Bind(R.id.empty)
    View mEmptyLayout;
    @Bind(R.id.ll)
    LinearLayout ll_view;
    @Bind(R.id.textView1)
    TextView textView1;
    @Bind(R.id.textView2)
    TextView textView2;
    @Bind(R.id.textView3)
    TextView textView3;
    @Bind(R.id.textView4)
    TextView textView4;
    @Bind(R.id.real_filterView)
    TextView real_filterView;
    public static final int HOTSPOT = 0;//热门
    public static final int CATE = 1;//美食
    public static final int LITE = 2;//生活
    public static final int TRAVEL = 3;//旅游
    public static final int TRST = 5;//其他
    protected String mNewsId;
    protected String mNewsType;
    protected static final String NEWS_ID = "news_id";
    protected static final String NEWS_TYPE = "news_type";
    private List<String> strings = new ArrayList<>();
    private boolean isFirstEnter = true;
    private boolean isFirst = false;
    private int type;
    private RecyclerView recyclerView;
    private UserEditAdapter rvAdapter;
    private ClassicsHeader mClassicsHeader;
    private Drawable mDrawableProgress;
    private int lastVisibleItem = 0;
    private GridLayoutManager layoutManager;
    private boolean isBottom = false;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mNewsId = getArguments().getString(NEWS_ID);
            mNewsType = getArguments().getString(NEWS_TYPE);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.activity_using_basic, container, false);
        ButterKnife.bind(this, view);
        ll_view.setAlpha(0f);
        TextView empty = (TextView) view.findViewById(R.id.empty_text);
        empty.setText("暂无数据点击刷新" + type);
        empty.setTextColor(Color.BLACK);
        empty.setTextSize(30);
        mClassicsHeader = (ClassicsHeader) mRefreshLayout.getRefreshHeader();
        mClassicsHeader.setSpinnerStyle(SpinnerStyle.Translate);//尺寸拉伸 //mClassicsHeader.setSpinnerStyle(SpinnerStyle.Translate);//位置平移
        int deta = new Random().nextInt(7 * 24 * 60 * 60 * 1000);
        mClassicsHeader = (ClassicsHeader) mRefreshLayout.getRefreshHeader();
        mClassicsHeader.setLastUpdateTime(new Date(System.currentTimeMillis() - deta));
        mClassicsHeader.setTimeFormat(new SimpleDateFormat("更新于 MM-dd HH:mm", Locale.CHINA));
        mClassicsHeader.setTimeFormat(new DynamicTimeFormat("更新于 %s"));
        //layoutManager = new MyStaggerGrildLayoutManger(getActivity(), 2, StaggeredGridLayoutManager.VERTICAL);
        layoutManager = new GridLayoutManager(getActivity(), 2);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        //防止item位置互换
        //manager.setGapStrategy(StaggeredGridLayoutManager.GAP_HANDLING_NONE);
        // 设置布局管理一条数据占用几行，如果是头布局则头布局自己占用一行
        layoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int postion) {
                if (postion < 8) {
                    return 2;
                } else {
                    return 1;
                }
            }
        });

        mDrawableProgress = mClassicsHeader.getProgressView().getDrawable();
        if (mDrawableProgress instanceof LayerDrawable) {
            mDrawableProgress = ((LayerDrawable) mDrawableProgress).getDrawable(0);
        }
        if (isFirstEnter) {
            isFirstEnter = false;
            mRefreshLayout.autoRefresh();//第一次进入触发自动刷新，演示效果
        }
        View views = view.findViewById(R.id.recyclerView);
        if (views instanceof RecyclerView) {
            recyclerView = (RecyclerView) views;
            recyclerView.setLayoutManager(layoutManager);
            recyclerView.addItemDecoration(new DividerGridItemDecoration(getActivity(), 20, R.color.blue));
            recyclerView.setItemAnimator(new DefaultItemAnimator());
            recyclerView.addOnScrollListener(scrollListener);
        }
        mRefreshLayout.setEnableAutoLoadmore(true);//开启自动加载功能（非必须）
        mRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(final RefreshLayout refreshlayout) {
                mRefreshLayout.getLayout().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        isFirst = false;
                        getDataView();
                        mRefreshLayout.finishRefresh();
                        mRefreshLayout.setLoadmoreFinished(false);
                        mEmptyLayout.setVisibility(View.GONE);

                    }
                }, 2000);
            }
        });
        mRefreshLayout.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(final RefreshLayout refreshlayout) {
                refreshlayout.getLayout().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        isFirst = true;
                        getDataView();
                        refreshlayout.finishLoadmore();
                        if (rvAdapter.getItemCount() > 20 && rvAdapter != null) {
                            Toast.makeText(getActivity(), "数据全部加载完毕", Toast.LENGTH_SHORT).show();
                            mRefreshLayout.setLoadmoreFinished(true);//将不会再次触发加载更多事件
                        }
                    }
                }, 2000);
            }
        });
        textView1.setOnClickListener(this);
        textView2.setOnClickListener(this);
        textView3.setOnClickListener(this);
        textView4.setOnClickListener(this);
        return view;
    }

    private boolean move = true;

    private int mIndex = 0;


    private void smoothMoveToPosition(int n) {

        int firstItem = layoutManager.findFirstVisibleItemPosition();
        int lastItem = layoutManager.findLastVisibleItemPosition();
        if (n <= firstItem) {
            recyclerView.smoothScrollToPosition(n);
        } else if (n <= lastItem) {
            int top = recyclerView.getChildAt(n - firstItem).getTop();
            recyclerView.smoothScrollBy(0, top);
        } else {
            recyclerView.smoothScrollToPosition(n);
            move = true;
        }

    }

    private void move(int n) {
        if (n < 0 || n >= rvAdapter.getItemCount()) {
            Toast.makeText(getActivity(), "超出范围了", Toast.LENGTH_SHORT).show();
            return;
        }
        mIndex = n;
        recyclerView.stopScroll();
        // moveToPosition(n);
        smoothMoveToPosition(n);

    }

    private void moveToPosition(int n) {
        //先从RecyclerView的LayoutManager中获取第一项和最后一项的Position
        int firstItem = layoutManager.findFirstVisibleItemPosition();
        int lastItem = layoutManager.findLastVisibleItemPosition();
        //然后区分情况
        if (n <= firstItem) {
            //当要置顶的项在当前显示的第一个项的前面时
            recyclerView.scrollToPosition(n);
        } else if (n <= lastItem) {
            //当要置顶的项已经在屏幕上显示时
            int top = recyclerView.getChildAt(n - firstItem).getTop();
            recyclerView.scrollBy(0, top);
        } else {
            //当要置顶的项在当前显示的最后一项的后面时
            recyclerView.scrollToPosition(n);
            //这里这个变量是用在RecyclerView滚动监听里面的
            move = true;
        }

    }

    RecyclerView.OnScrollListener scrollListener = new RecyclerView.OnScrollListener() {
        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            handleTitleBarColorEvaluate(recyclerView);
            lastVisibleItem = layoutManager.findLastVisibleItemPosition();
            int n = Math.abs(mIndex - layoutManager.findFirstVisibleItemPosition());
            if (n == 0) {
                textView1.setText("我是0");
                textView1.setTextColor(Color.RED);
                textView2.setTextColor(Color.BLACK);
                textView3.setTextColor(Color.BLACK);
                textView4.setTextColor(Color.BLACK);
            } else if (n == 2) {
                textView2.setText("我是2");
                textView1.setTextColor(Color.BLACK);
                textView3.setTextColor(Color.BLACK);
                textView4.setTextColor(Color.BLACK);
                textView2.setTextColor(Color.LTGRAY);
            } else if (n == 4) {
                textView3.setText("我是4");
                textView3.setTextColor(Color.BLUE);
                textView2.setTextColor(Color.BLACK);
                textView1.setTextColor(Color.BLACK);
                textView4.setTextColor(Color.BLACK);
            } else if (n == 6) {
                textView4.setText("我是6");
                textView2.setTextColor(Color.BLACK);
                textView1.setTextColor(Color.BLACK);
                textView3.setTextColor(Color.BLACK);
                textView4.setTextColor(Color.GREEN);
            } else if (n >= 7) {
                real_filterView.setVisibility(View.VISIBLE);
            } else {
                real_filterView.setVisibility(View.GONE);
            }
        }

        public void onScrollStateChanged(RecyclerView recyclerView,
                                         int newState) {
            if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                if (rvAdapter != null)
                    isBottom = rvAdapter.getItemCount() - 1 == lastVisibleItem;
            }
        }
    };
    private int bannerViewTopMargin = 50; // 广告视图距离顶部的距离
    private int bannerViewHeight = 50; // 广告视图的高度
    private int titleViewHeight = 50; // 标题栏的高度
    private View itemHeaderBannerView; // 获取的子View
    private boolean isFirsts;

    // 处理标题栏颜色渐变
    private void handleTitleBarColorEvaluate(RecyclerView recyclerView) {
        itemHeaderBannerView = recyclerView.getChildAt(0);
        if (itemHeaderBannerView != null && isFirsts == false) {
            bannerViewTopMargin = DensityUtil.px2dip(getActivity(), itemHeaderBannerView.getTop());
            bannerViewHeight = DensityUtil.px2dip(getActivity(), itemHeaderBannerView.getHeight());
        }
        if (itemHeaderBannerView.getHeight() == 607) {
            float fraction;
            if (bannerViewTopMargin > 0) {
                fraction = 1f - bannerViewTopMargin * 1f / 60;
                if (fraction < 0f) fraction = 0f;
                ll_view.setAlpha(fraction);
                isFirsts = true;
                return;
            }
            float space = Math.abs(bannerViewTopMargin) * 1f;
            fraction = space / (bannerViewHeight - titleViewHeight);
            if (fraction < 0f)
                fraction = 0f;
            if (fraction > 1f)
                fraction = 1f;
            ll_view.setAlpha(fraction);
            if (fraction >= 1f) {
                ll_view.setBackgroundColor(getActivity().getResources().getColor(R.color.colorPrimary));
            } else {
                ll_view.setBackgroundColor(ColorUtil.getNewColorByStartEndColor(getActivity(), fraction, R.color.transparent, R.color.colorPrimary));
            }
        }
    }

    public static OrderFragment newInstance(int newsId) {
        OrderFragment fragment = new OrderFragment();
        Bundle bundle = new Bundle();
        bundle.putInt(NEWS_ID, newsId);
        fragment.type = newsId;// 0,1,2,3
        fragment.setArguments(bundle);
        return fragment;
    }

    private void getDataView() {
        switch (type) {
            case HOTSPOT://热门
                if (isFirst == true) {
                    recyclerView.scrollToPosition(lastVisibleItem);
                    rvAdapter.insert("30", rvAdapter.getItemCount());
                    rvAdapter.insert("30", rvAdapter.getItemCount());
                } else {
                    strings.removeAll(strings);
                    strings.add("0");
                    strings.add("1");
                    strings.add("2");
                    strings.add("3");
                    strings.add("4");
                    strings.add("5");
                    strings.add("6");
                    strings.add("7");
                    strings.add("8");
                    strings.add("9");
                    strings.add("10");
                }
                break;
            case CATE://美食
                if (isFirst == true) {
                    rvAdapter.insert("他", rvAdapter.getItemCount());
                    rvAdapter.insert("他", rvAdapter.getItemCount());
                    recyclerView.scrollToPosition(lastVisibleItem);
                } else {
                    strings.removeAll(strings);
                    strings.add("你");
                    strings.add("我");
                    strings.add("他");
                }
                break;
            case LITE://生活
                if (isFirst == true) {
                    rvAdapter.insert("他", rvAdapter.getItemCount());
                    rvAdapter.insert("他", rvAdapter.getItemCount());
                    recyclerView.scrollToPosition(lastVisibleItem);
                } else {
                    strings.removeAll(strings);
                    strings.add("羊");
                    strings.add("猪");
                    strings.add("鼠");
                }
                break;
            case TRAVEL://旅游
                if (isFirst == true) {
                    rvAdapter.insert("他", rvAdapter.getItemCount());
                    rvAdapter.insert("他", rvAdapter.getItemCount());
                    rvAdapter.insert("他", rvAdapter.getItemCount());
                    rvAdapter.insert("他", rvAdapter.getItemCount());
                    recyclerView.scrollToPosition(lastVisibleItem);
                } else {
                    strings.removeAll(strings);
                    strings.add("小");
                    strings.add("中");
                    strings.add("大");
                }

                break;
            case TRST:
                if (isFirst == true) {
                    rvAdapter.insert("他", rvAdapter.getItemCount());
                    rvAdapter.insert("他", rvAdapter.getItemCount());
                    recyclerView.scrollToPosition(lastVisibleItem);
                } else {
                    strings.removeAll(strings);
                    strings.add("10");
                    strings.add("11");
                    strings.add("12");
                }
                break;
        }
        rvAdapter = new UserEditAdapter(getActivity(), strings);
        recyclerView.setAdapter(rvAdapter);
        rvAdapter.notifyDataSetChanged();
        rvAdapter.setmOnItemClickLitener(new UserEditAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View v, int postion) {
                smoothMoveToPosition(3);
                Toast.makeText(getActivity(), "----" + postion, Toast.LENGTH_LONG).show();
            }

            @Override
            public void onItemLongClick(View v, int postion) {
                moveToPosition(0);
            }
        });

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        rvAdapter.stopBanner();
    }

    @Override
    public void onStop() {
        super.onStop();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.textView1:
                smoothMoveToPosition(0);
                break;
            case R.id.textView2:
                smoothMoveToPosition(2);
                break;
            case R.id.textView3:
                smoothMoveToPosition(4);
                break;
            case R.id.textView4:
                smoothMoveToPosition(6);
                // moveToPosition(6);
                break;
        }
    }
}
